package otcv.hr.webapp.action.login;

import java.sql.SQLException;
import java.util.ResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import otcv.hr.controller.ActionServlet;
import otcv.hr.util.Util;
import otcv.hr.webapp.dao.LoginDAO;
import otcv.hr.webapp.entity.LoginEntity;
import otcv.hr.webapp.entity.LoginSchEntity;

/**
 * @author : H-Thien
 * @comment : Login Process Action
 */
public class LoginProcAction extends ActionServlet {

	private ResourceBundle bundle = ResourceBundle.getBundle("URL");

	@Override
	protected String getURL() {
		return bundle.getString("LOGIN_PROC_ACTION");
	}

	@Override
	public void process(ServletContext sc, HttpServletRequest req,
			HttpServletResponse res) throws Exception {

		LoginSchEntity loginSchEntity = new LoginSchEntity();

		loginSchEntity.setSch_username(Util.nullTo(
				req.getParameter("username"), ""));

		loginSchEntity.setSch_password(Util.nullTo(
				req.getParameter("password"), ""));

		try {
			LoginDAO dao = new LoginDAO();
			LoginEntity loginEntity = new LoginEntity();
			loginEntity = dao.login(loginSchEntity);

			boolean loginYn = false;
			if (loginEntity != null) {
				loginYn = true;

				// session
				HttpSession session = req.getSession();
				session.setAttribute("ses_check", "live");
				session.setAttribute("ses_user_fname",
						loginEntity.getFirst_name());
				session.setAttribute("ses_user_lname",
						loginEntity.getLast_name());
				session.setAttribute("ses_user_username",
						loginEntity.getUsername());
				session.setAttribute("ses_user_staffid",
						loginEntity.getStaff_id());
			}
			req.setAttribute("login_yn", loginYn);
		} catch (Exception se) {
			throw new SQLException(se.toString());
		}
	}
}